<template>
  <div>
    <ConditionCard body-style="padding: 24px 24px 6px;" @search="search" @reset="reset">
      <el-form :model="condition" label-width="100px" ref="conditionForm">
        <el-row :gutter="24">
          <el-col :span="8">
            <el-form-item :label="$t('label.grade') + ':'" prop="grade">
              <el-select v-model="condition.grade" @change="selectChange" style="width: 100%" filterable clearable>
                <el-option v-for="item in options.grade" :key="item.id" :label="item.value" :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item :label="$t('label.college') + ':'" prop="college">
              <el-select v-model="condition.college" @change="selectChange" style="width: 100%" filterable clearable>
                <el-option v-for="item in options.college" :key="item.key" :label="item.label" :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item :label="$t('label.major') + ':'" prop="professional">
              <el-select v-model="condition.professional" @change="professionChange" style="width: 100%" filterable
                clearable>
                <el-option v-for="item in options.professional" :key="item.key" :label="item.label" :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24">
          <el-col :span="8">
            <el-form-item :label="$t('auditStandard.proDirection') + ':'" prop="proDirection">
              <el-select v-model="condition.direction" style="width: 100%" filterable clearable>
                <el-option v-for="item in options.direction" :key="item.key" :label="item.label" :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </ConditionCard>
    <el-card shadow="never" body-style="padding: 0 24px 24px;">
      <div v-if="professionalTableData[0] && professionalTableData[0].data.length" class="professionalTable">
        <div class="clearfix" style="margin-bottom:16px">
          <div class="edu-page-title">{{$t("auditStandard.creditStandard")}}</div>
        </div>
        <edu-table :data="professionalTableData" :order="false" :pagination="false" border :selection="false"
          :merge='true' :stripe="false" :headerCellStyle="headerCellStyle">
          <edu-table-column  align="center" :label="$t('label.courseCategory')" width="150">
            <template slot-scope="scope">
              <div v-if="scope.row.courseCategory">
                {{scope.row.courseCategory}}
              </div>
            </template>
          </edu-table-column>
          <edu-table-column  align="center" :label="item.labName" min-width="150"
            v-for="(item, key)  in professionalTableData[0].data" :key='key'>
            <template slot-scope="scope">
              <div v-if="scope.row.data[key]">{{scope.row.data[key].credit}}</div>
            </template>
          </edu-table-column>
        </edu-table>
      </div>
      <div style="margin-top: 24px" v-if="generalCourseTableData[1] && generalCourseTableData[1].data.length">
        <edu-table :data="generalCourseTableData" :order="false" :pagination="false" border :selection="false"
          :merge='true' :show-header="false" :stripe="false" :rowStyle="rowStyle" style="width: 100%;">
          <edu-table-column v-for="(item, key) in generalCourseTableData[1].data" :key="key" min-width="250">
            <template slot-scope="scope">
              <div v-if="scope.row.data[key]">
                <div class="float-left" style="width: 150px;text-align: right;margin-right: 20px;">
                  {{scope.row.data[key].labName}}:</div>
                <div class="float-left">
                  <div v-text="scope.row.data[key].credit"></div>
                </div>
              </div>
            </template>
          </edu-table-column>
        </edu-table>
      </div>
    </el-card>
  </div>

</template>
<script>
  import {
    GRADUATIONYEAR
  } from '../components/gradMangeUtis';
  import {
    queryDic
  } from "common/src/api/dictionary";
  import UTILS from "common/src/utils/utils";
  import api from 'common/src/api/graduationManagement/graduationManage';
  export default {
    data() {
      return {
        condition: {
          grade: '',
          college: '',
          professional: '',
          direction: ''
        },
        options: {
          grade: GRADUATIONYEAR,
          college: [],
          professional: [],
          direction: []
        },
        professionalTableData: [],
        generalCourseTableData: [],
        isOverseas: '0'
      }
    },
    created() {
      this.initCollageOption();
    },
    methods: {
      initCollageOption() {
        const data = {
          lang: this.$store.getters.language || "cn",
          type: "allChild",
          keys: ["X_YX"]
        };
        queryDic(data).then(res => {
          if (res.code === 200) {
            UTILS.fillSelect({
                college: "X_YX"
              },
              res.data,
              this.options
            );
          }
        });
      },
      initProfessionalOption() {
        if (!this.condition.college || !this.condition.grade) {
          return;
        }
        let param = {
          faculty: this.condition.college,
          grade: this.condition.grade,
          pageNum_: 1,
          pageSize_: 100,
          projId: "1"
        }
        this.options.professional = [];
        this.condition.professional = '';
        api.getProfessionList(param).then(res => {
          if (res && res.code === 200) {
            let listData = res.data && res.data.list || [];
            let options = [];
            listData.forEach(item => {
              if (item.professionCode) {
                options.push({
                  key: item.professionCode,
                  value: item.professionCode,
                  label: item.professionName
                })
              }
            })
            this.options.professional = options;
          }
        })
      },
      initDirection() {
        if (this.condition.grade && this.condition.professional) {
          let params = {
            pageNum_: 1,
            pageSize_: 20,
            grade: this.condition.grade,
            professionCode: this.condition.professional
          };
          this.options.direction = [];
          this.condition.direction = '';
          api.findDirMaintenList(params).then(res => {
            if (res && res.code === 200) {
              let listData = res.data && res.data.list || [];
              let options = [];
              listData.forEach(item => {
                if (item.code) {
                  options.push({
                    key: item.code,
                    value: item.code,
                    label: item.name
                  })
                }
              })
              this.options.direction = options;
            }
          })
        }

      },
      selectChange() {
        this.initProfessionalOption();
      },
      professionChange() {
        this.initDirection();
      },
      reset() {
        this.$refs.conditionForm.resetFields();
        this.professionalTableData = [];
        this.generalCourseTableData = [];
      },
      search() {
        this.getStandard();
      },
      getStandard() {
        if (this.condition.grade) {
          this.professionalTableData = [];
          this.generalCourseTableData = [];
          let params = {
            ...this.condition,
            isOverseas: this.isOverseas
          };
          api.geStandardLabel(params).then(res => {
            if (res && res.code === 200) {
              let {
                labelStandard,
                ElectiveStandard
              } = res.data || {};
              this.handleLabelStandard(labelStandard);
              this.handleElectiveStandard(ElectiveStandard);
            }
          })
        }
      },
      handleLabelStandard(data) {
        if (!data) {
          return;
        }
        let labIdMap = {};
        let totalItem = null;
        let list = data.filter(item => {
          item.credit = item.credit || 0;
          if (item.orderNum === 999) {
            totalItem = item;
          } else {
            if (!item.parentLabID) {
              let labID = item.labID + '_';
              if (!labIdMap[labID]) {
                labIdMap[labID] = [];
              }
              labIdMap[labID].push(item);
            } else {
              let parentLabID = item.parentLabID + '_';
              if (!labIdMap[parentLabID]) {
                labIdMap[parentLabID] = [];
              }
              labIdMap[parentLabID].push(item);
            }
          }
          return item.orderNum !== 999;
        });
        let newList = [{
            courseCategory: this.$t('auditStandard.creditRequirements'),
            data: []
          },
          {
            courseCategory: this.$t('auditStandard.creditTotal'),
            data: []
          },
          {
            courseCategory: this.$t('auditStandard.totalCredits'),
            data: [totalItem]
          }
        ];
        for (let key in labIdMap) {
          labIdMap[key].sort((item1, item2) => {
            return item2.orderNum - item1.orderNum;
          })
          let len = newList[1].data.length;
          if (labIdMap[key] && labIdMap[key].length > 1) {
            let num = 0;
            labIdMap[key].forEach(v => {
              if (v.parentLabID) {
                newList[0].data.push(v);
                num++;
              } else {
                newList[1].data.push(v);
              }
            })
            if (!newList[1].columnList) {
              newList[1].columnList = [];
            }
            num > 1 && (newList[1].columnList.push({
              index: len + 1,
              rowspan: 1,
              colspan: num
            }));
          } else {
            if (labIdMap[key].length === 1) {
              newList[0].data.push(labIdMap[key][0]);
              newList[1].data.push(labIdMap[key][0]);
            }
          }
        }
        let totalNum = newList[0].data.length;
        newList[2].columnList = [{
          index: 1,
          rowspan: 1,
          colspan: totalNum
        }];
        this.professionalTableData = newList;
      },
      handleElectiveStandard(param) {
        if (!param) {
          return;
        }
        let totals = 0;
        let data = param.filter(v => {
          if (v.orderNum === 999) {
            totals = v.credit;
          }
          return v.orderNum !== 999;
        })
        let len = data.length;
        let index = 1;
        let list = [{
          data: [{
            labName: this.$t('auditStandard.creditStandardGeneralCourses'),
            credit: 0
          }]
        }];
        let calcuTotal = 0;
        for (let i = 0; i < len; i++) {
          data[i].credit && (calcuTotal += Number(data[i].credit));
          if (i !== 0 && i % 4 === 0) {
            index++;
          }
          if (!list[index]) {
            list[index] = {
              data: []
            };
          }
          data[i].credit = data[i].credit || 0;
          list[index].data.push(data[i]);
        }
        list[0].columnList = [{
            index: 0,
            rowspan: 1,
            colspan: list[1].data.length
          }],
          list[0].data[0].credit = totals || calcuTotal;
        this.generalCourseTableData = list;
      },
      headerCellStyle() {
        return "background: #f4f7fa";
      },
      rowStyle({
        rowIndex
      }) {
        if (rowIndex === 0) {
          return "background: #f4f7fa";
        }
      }

    },

  }

</script>
<style scoped lang="scss">
  .professionalTable ::v-deep .cell.el-tooltip {
    margin: 0 auto;
  }

  .professionalTable ::v-deep .el-table__row:last-child {
    background: #f4f7fa;

    & td:first-child {
      border-right: none;
    }
  }

</style>
